package com.wechat.server.mp.interceptor;

import cn.hutool.core.util.StrUtil;
import com.wechat.server.mp.config.PddConfig;
import com.wechat.server.mp.service.PddService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 授权拦截
 * @author: stone
 * @date: Created by 2021/10/9 11:29
 * @version: 1.0.0
 * @pakeage: com.wechat.server.mp.interceptor
 */
@Component("authInterceptor")
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {


    @Autowired
    private PddConfig.PddProperties pddProperties;


    @Autowired
    private PddService pddService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
            String token = (String) PddConfig.cacheToken.get("token");
            log.info("拦截 ====>  {}",request.getRequestURI());
            //Long expire = (Long) PddConfig.cacheToken.get("expire");
            if (StrUtil.isNotBlank(token) && pddService.checkToken()) {
                return true;
            }
            response.sendRedirect( pddProperties.getAuthUrl()+ "?response_type=code&client_id="+pddProperties.getClientId() +"&state=code&redirect_uri=" + pddProperties.getClientUrl());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作

    }
}
